﻿using CDH_VoteSys.Models;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace CDH_VoteSys.service
{
	/// <summary>
	/// 认证处理服务
	/// </summary>
	public class JWTService :IJWTService
	{
		/// <summary>
		/// JWT配置信息
		/// </summary>
		private readonly JWTConfig _jwtConfig;

		/// <summary>///
		/// 通过构造注入 JWT配置信息
		/// </summary>
		/// <param name="jwtConfig"></param>
		public JWTService(IOptions<JWTConfig> jwtConfig)
		{
			this._jwtConfig = jwtConfig.Value;
		}
		/// <summary>
		/// 实现接口方法 创建Token
		/// </summary>
		/// <param name="uId"></param>
		/// <param name="uName"></param>
		/// <returns></returns>
		public string CreateToken(int uId, string uName, string uEmail)
		{
			//登录信息的载荷 
			//把有需要的信息写到Token
			var claims = new[] {
                //预定义好的类型
                //用户Id
                new Claim(ClaimTypes.NameIdentifier, uId.ToString()),
                //用户名
                new Claim(ClaimTypes.Name, uName),
				new Claim(ClaimTypes.Email,uEmail),
				new Claim(ClaimTypes.MobilePhone,""),
                //设置自定义载荷体类型
                new Claim("QQ","")

			};

			//创建密钥类
			var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConfig.Secret));
			//密钥加密
			var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

			//token配置 创建TOKEN配置
			var jwtToken = new JwtSecurityToken(_jwtConfig.Issuer,
				_jwtConfig.Audience,
				claims,
				//          当前时间+多少分钟（AccessExpiration）
				expires: DateTime.Now.AddMinutes(_jwtConfig.AccessExpiration),
				signingCredentials: credentials);

			//获取token 
			var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
			return token;
		}
	}
}
